package com.yunc.base.security.filter;

import cn.hutool.json.JSONUtil;
import com.yunc.base.security.UserEntity;
import com.yunc.base.service.RedisService;
import com.yunc.base.utils.JwtTokenUtils;
import com.yunc.base.utils.R;
import com.yunc.base.utils.SpringContextUtils;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token校验
 *
 * @author taocongcong
 * @create 2019-10-12 9:32
 */
public class JWTAuthorizationFilter extends BasicAuthenticationFilter {

    private static final String AUTH_TOKEN = "auth_user_";

    private RedisService redisService = (RedisService) SpringContextUtils.getBean("redisService");

    public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {
        String tokenHeader = getRequestParameter(request, JwtTokenUtils.TOKEN_HEADER);
        // 如果请求头中没有Authorization信息则直接放行了
        if (tokenHeader == null || !tokenHeader.startsWith(JwtTokenUtils.TOKEN_PREFIX)) {
            chain.doFilter(request, response);
            return;
        }
        response.setContentType("application/json; charset=utf-8");
        String token = tokenHeader.replace(JwtTokenUtils.TOKEN_PREFIX, "");
        // 查询redis
        String userId = null;
        try {
            userId = JwtTokenUtils.getUserId(token);
        } catch (MalformedJwtException e) {
            response.getWriter().write(JSONUtil.toJsonStr(R.error(HttpServletResponse.SC_FORBIDDEN, "Token format error")));
            return;
        } catch (ExpiredJwtException e) {
            response.getWriter().write(JSONUtil.toJsonStr(R.error(HttpServletResponse.SC_FORBIDDEN, "Token expired")));
            return;
        }
        UserEntity user = (UserEntity) redisService.hget(AUTH_TOKEN + userId, token);
        if (user == null) {
            // filter中无法经过异常处理器
            // throw new UCException( "您已退出登录", 403);
            response.getWriter().write(JSONUtil.toJsonStr(R.error(HttpServletResponse.SC_FORBIDDEN, "您已退出登录")));
            return;
        }
        // 如果请求头中有token，则进行解析，并且设置认证信息
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        super.doFilterInternal(request, response, chain);
    }

    private String getRequestParameter(HttpServletRequest httpRequest, String parameter) {
        String requestParameter = httpRequest.getHeader(parameter);
        if (StringUtils.isBlank(requestParameter)) {
            requestParameter = httpRequest.getParameter(parameter);
        }
        return requestParameter;
    }
}
